package com.autumn.platform.web.exceptionresolver;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.AbstractHandlerMapping;

public class ExceptionHandlerMapping extends AbstractHandlerMapping {

    /**
     * 异常信息存储在请求中的属性名称
     */
    private static final String EXCEPTION_IN_REQUEST_ATTR_NAME = ExceptionHandlerMapping.class.getName() + ".EXCEPTION_IN_REQUEST_ATTR_NAME";

    private static Method method;

    static {
        try {
            method = ExceptionHandlerMapping.class.getDeclaredMethod("doHandlerException", HttpServletRequest.class);
        } catch (Exception e) {
        }
    }

    /**
     * 构造函数，设置高优先级
     */
    public ExceptionHandlerMapping() {
        super();
        super.setOrder(HIGHEST_PRECEDENCE);
    }

    public static void setExceptionToRequestContext(HttpServletRequest request, Exception exception) {
        request.setAttribute(EXCEPTION_IN_REQUEST_ATTR_NAME, exception);
    }

    @ResponseBody
    public Object doHandlerException(HttpServletRequest request) throws Exception {
        Exception exception = (Exception) request.getAttribute(EXCEPTION_IN_REQUEST_ATTR_NAME);
        throw exception;
    }

    /**
     * 获取处理器
     */
    @Override
    protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
        Object exception = request.getAttribute(EXCEPTION_IN_REQUEST_ATTR_NAME);
        if (exception instanceof Exception) {
            return new HandlerMethod(this, method);
        }
        return null;
    }
}
